ifndef TOP
TOP:=$(shell X=..; until stat $$X/topstamp 1>/dev/null 2>/dev/null;do X=$$X/..; done;echo $$X)
endif

ifndef DIR
pwd := $(shell pwd;)
DIR:=$(shell basename $(pwd);)
endif

ACFLAGS ?= -v1 -k
AC      ?= $(TOP)/third/ac++
AG      ?= $(TOP)/third/ag++
PCONFIG ?= $(TOP)/third/puma.config
CC =g++
LIBRARY_PATH =$(TOP)/third/libantlr3c/.libs

.PHONY: clean

ext=
preprocessor= 
d_ext=
comp_ext=
a_ext=
ifeq ($(findstring debug,$(MAKECMDGOALS)),debug)
	d_ext=-g
	preprocessor+= -g -DDEBUG
endif
ifeq ($(findstring compact,$(MAKECMDGOALS)),compact)
	comp_ext=-comp
	preprocessor+= -DCOMPACT
endif

ifeq ($(findstring 32,$(MAKECMDGOALS)),32)
	preprocessor+= -m32
else
	preprocessor+= -m64
endif

remove =$(TOP)/.objs/*.o *.d
ifeq ($(findstring gmini.g,$(GSOURCES)),gmini.g)
	objects= $(objects_temp) gminiParser.o gminiLexer.o
	remove+= gminiLexer.c gminiParser.c gminiLexer.h gminiParser.h
else
	objects= $(objects_temp)
endif

ifeq ($(findstring text,$(MAKECMDGOALS)),text)
	visitor= $(TOP)/src/graph/visitor.h
else
	inc= -I$(TOP)/src/aspectout/graph
	visitor= $(TOP)/src/aspectout/graph/visitor.h
	ifeq ($(findstring graph,$(DIR)),graph)
		remove+= -r $(TOP)/src/aspectout/
	endif
	a_ext=-a
endif

libs=-L$(LIBRARY_PATH)
gmini_t=gmini$(d_ext)$(a_ext)$(comp_ext)

aspectfile= $(TOP)/src/visual/AShapeVisitor.ah

inc+= -I$(TOP)/src/main -I$(TOP)/src/visual -I$(TOP)/src/grammar -I$(TOP)/src/translate -I$(TOP)/src/check -I$(TOP)/src/graph -I.

#inc += -I$(TOP)/third/

CSOURCES=${wildcard *.c}
GSOURCES=${wildcard *.g}
HSources=${wildcard *.h}

objects_temp=$(CSOURCES:.c=.o)

full_objects=$(addprefix $(TOP)/.objs/,$(objects))

depends=$(objects:.o=.d)

ifeq ($(findstring graph,$(DIR)),graph)
	targets=$(TOP)/src/aspectout/graph/visitor.h $(TOP)/lib/lib$(DIR)
else
	targets=$(TOP)/lib/lib$(DIR)
endif


.PHONY: clean

all : $(targets)

ifeq ($( findstring $( MAKECMDGOALS ), clean ),)
-include $(depends)
endif

$(TOP)/lib/lib$(DIR) : $(full_objects)
	ar rcs $@.a $(full_objects)

$(TOP)/src/aspectout/graph/visitor.h: $(TOP)/src/graph/visitor.h $(aspectfile)
	$(AC) $(ACFLAGS) --config $(PCONFIG) $(inc) -p $(TOP)/src/ -a $(aspectfile) -c $< -d $(TOP)/src/aspectout/

%.d : %.c
	$(CC) $(inc) $(preprocessor) -M $<  > $@

$(TOP)/.objs/%.o : %.c 
	$(CC) -o $(TOP)/.objs/$*.o -c $(inc) $*.c $(preprocessor)

gminiParser.c gminiParser.h gminiLexer.c gminiLexer.h: gmini.g 
	java -jar $(TOP)/third/antlr-3.2.jar $<

clean:
	rm $(remove)
